package com.abdosoft.core;

import org.apache.commons.lang.StringUtils;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class StringUtil extends StringUtils {

    /**
     * 生成随机字符串
     *
     * @param length
     * @return
     */
    public static String getRandomString(int length) { //length表示生成字符串的长度
        String base = "aAbBcCdDeEfFgGhHijklLmMnNopqQrRstYuvwxyYz0123456789";
        Random random = new Random();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < length; i++) {
            int number = random.nextInt(base.length());
            sb.append(base.charAt(number));
        }
        return sb.toString();
    }

    public static String getRandomStringNum(int length) { //length表示生成字符串的长度
        String base = "0123456789";
        Random random = new Random();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < length; i++) {
            int number = random.nextInt(base.length());
            sb.append(base.charAt(number));
        }
        return sb.toString();
    }

    /**
     * 取得一个字符串
     *
     * @param str
     * @param def
     * @return
     */
    public static String getString(String str, String def) {
        try {
            if (StringUtil.isEmpty(str) || "null".equals(str) || "(null)".equals(str) || "\"null\"".equals(str)) {
                return def;
            }
            return str;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return def;
    }

    public static String getString(String str) {
        try {
            if (StringUtil.isEmpty(str)) {
                return "";
            }
            return str;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }


    /*
     * 字符串转int
     */
    public static int getInt(String str, int def) {

        try {
            str = getNUM(str);
            if (StringUtil.isEmpty(str)) {
                return def;
            }
            return Integer.parseInt(str, 10);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return def;
    }

    public static int getInt(String str) {
        try {
            str = getNUM(str);
            if (StringUtil.isEmpty(str) || "null".equals(str)) {
                return 0;
            }
            return Integer.parseInt(str, 10);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }

    public static long getLong(String str, long def) {
        try {
            if (StringUtil.isEmpty(str) || "null".equals(str)) {
                return def;
            }
            return Long.parseLong(str, 10);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return def;
    }

    public static long getLong(String str) {
        try {
            if (StringUtil.isEmpty(str) || "null".equals(str)) {
                return 0;
            }
            return Long.valueOf(str);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }

    public static double getDouble(String str, double def) {
        try {
            if (StringUtil.isEmpty(str) || "null".equals(str)) {
                return def;
            }
            return Double.parseDouble(str);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return def;
    }


    public static double getDouble(double str, int xiaoshu) {
        try {
            if (xiaoshu == 1) {
                return ((int) (str * 10)) / 10.0;
            } else if (xiaoshu == 2) {
                return ((int) (str * 100)) / 100.00;
            } else if (xiaoshu == 3) {
                return ((int) (str * 1000)) / 1000.0;
            } else if (xiaoshu == 4) {
                return ((int) (str * 10000)) / 10000.0;
            } else if (xiaoshu == 5) {
                return ((int) (str * 100000)) / 100000.0;
            } else {
                return str;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return str;
    }

    public static double getDouble(String str, double def, int xiaoshu) {
        try {
            if (StringUtil.isEmpty(str) || "null".equals(str)) {
                return def;
            }
            if (xiaoshu == 1) {
                return ((int) (Double.parseDouble(str) * 10)) / 10.0;
            } else if (xiaoshu == 2) {
                return ((int) (Double.parseDouble(str) * 100)) / 100.00;
            } else if (xiaoshu == 3) {
                return ((int) (Double.parseDouble(str) * 1000)) / 1000.0;
            } else if (xiaoshu == 4) {
                return ((int) (Double.parseDouble(str) * 10000)) / 10000.0;
            } else if (xiaoshu == 5) {
                return ((int) (Double.parseDouble(str) * 100000)) / 100000.0;
            } else {
                return Double.parseDouble(str);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return def;
    }


    public static double getDouble(String str) {
        try {
            if (StringUtil.isEmpty(str) || "null".equals(str)) {
                return 0.0;
            }
            return Double.parseDouble(str);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0.0;
    }

	/*
     * 取得唯一编号
	 */

    public static String getUUID(String head, String tail) {
        String tmpS = head.substring(0, 1);
        tmpS = tmpS + (new SimpleDateFormat("yyMMddHHmmSSS")).format(new Date());
        return tmpS + tail.substring(0, 1) + String.format("%04d", (int) (Math.random() * 10000));
    }

    public String getUUID(String head, String tail, int seq) {
        String tmpS = head.substring(0, 1);
        tmpS = tmpS + (new SimpleDateFormat("yyMMddHHmmSSS")).format(new Date());
        return tmpS + tail.substring(0, 1) + String.format("%04d", (int) (seq));
    }


    /* 
     * 将bean初始化为map,初始化生成要返回的表格
     */
    public static HashMap<String, String> getMapForBean(Object obj) {

        HashMap<String, String> map = new HashMap<String, String>();
        try {
            Class toClazz = Class.forName(obj.getClass().getName());
            Field[] toFields = toClazz.getDeclaredFields();// 根据Class对象获得属性

            for (Field toFild : toFields) {
                // System.out.println(f.getType().getName());//打印每个属性的类型名字
                String toName = toFild.getName();
                if (!"tables".equals(toName)) {
                    String totype = toFild.getGenericType().toString(); // 获取属性的类型
                    String name = toName.substring(0, 1).toUpperCase() + toName.substring(1); // 将属性的首字符大写，方便构造get，set方法
                    try {
                        Object value = null;
                        try {
                            Method srcGetM = obj.getClass().getMethod("get" + name);
                            if (srcGetM != null) {
                                value = srcGetM.invoke(obj);
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                        toName = toName.toLowerCase();
                        if (totype.equals("class java.lang.String")) {   //如果type是类类型，则前面包含"class "，后面跟类名
                            if (value != null && StringUtil.isNotEmpty(value.toString())) {
                                map.put(toName, value.toString());
                            } else {
                                if (toName.indexOf("id") >= 0) {
                                    map.put(toName, getUUID("I", "D"));
                                } else {
                                    map.put(toName, "");
                                }
                            }
                        }
                        if (totype.equals("class java.lang.Integer")) {
                            if (value != null && StringUtil.isNotEmpty((Integer) value)) {
                                map.put(toName, value.toString());
                            } else {
                                map.put(toName, "0");
                            }
                        }
                        if (totype.equals("class java.lang.Short")) {
                            if (value != null && StringUtil.isNotEmpty((Integer) value)) {
                                map.put(toName, value.toString());
                            } else {
                                map.put(toName, "0");
                            }
                        }
                        if (totype.equals("class java.lang.Double")) {
                            if (value != null && StringUtil.isNotEmpty((Double) value)) {
                                map.put(toName, value.toString());
                            } else {
                                map.put(toName, "0.0");
                            }
                        }
                        if (totype.equals("class java.lang.Boolean")) {
                            if (value != null && (Boolean) value) {
                                map.put(toName, "true");
                            } else {
                                map.put(toName, "false");
                            }
                        }
                        if (totype.equals("class java.util.Date")) {
                            if (value != null) {
                                /** 输出格式: 2006-01-01 00:00:00 */
                                map.put(toName, new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(value));
                            } else {
                                map.put(toName, new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date()));
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }

        } catch (Exception e) {
            //
        } finally {

        }
        return map;
    }


    /**
     * 对象赋值:srcObj与toObj中相同属性，将从 srcObj给toObj
     */
    public static boolean CopyObj(Object srcObj, Object toObj) {

        Boolean re = false;
        try {
			/* 数据来源 */
            Class srcClazz = Class.forName(srcObj.getClass().getName());// 根据类名获得其对应的Class对象
            // 写上你想要的类名就是了
            // 注意是全名
            // 如果有包的话要加上
            // 比如java.Lang.String
            Field[] srcFields = srcClazz.getDeclaredFields();// 根据Class对象获得属性
            // 私有的也可以获得

			/* 目标对象 */
            Class toClazz = Class.forName(toObj.getClass().getName());
            Field[] toFields = toClazz.getDeclaredFields();// 根据Class对象获得属性
            // 私有的也可以获得

            for (Field srcfild : srcFields) {
                // System.out.println(f.getType().getName());//打印每个属性的类型名字
                String srcName = srcfild.getName(); // 获取属性的名字
                String srctype = srcfild.getGenericType().toString(); // 获取属性的类型

                for (Field toFild : toFields) {
                    String toName = toFild.getName();
                    String totype = toFild.getGenericType().toString(); // 获取属性的类型
                    if (srcName.equals(toName) && srctype.equals(totype)) {// 共同有的属性
                        String name = toName.substring(0, 1).toUpperCase() + toName.substring(1); // 将属性的首字符大写，方便构造get，set方法
                        try {
                            Method srcGetM = srcObj.getClass().getMethod("get" + name);
                            Method toGetM = null;
                            if (totype.equals("class java.lang.String")) {   //如果type是类类型，则前面包含"class "，后面跟类名
                                toGetM = toObj.getClass().getMethod("set" + name, String.class);
                            }
                            if (totype.equals("class java.lang.Integer")) {
                                toGetM = toObj.getClass().getMethod("set" + name, Integer.class);
                            }
                            if (totype.equals("class java.lang.Short")) {
                                toGetM = toObj.getClass().getMethod("set" + name, Short.class);
                            }
                            if (totype.equals("class java.lang.Double")) {
                                toGetM = toObj.getClass().getMethod("set" + name, Double.class);
                            }
                            if (totype.equals("class java.lang.Boolean")) {
                                toGetM = toObj.getClass().getMethod("set" + name, Boolean.class);
                            }
                            if (totype.equals("class java.util.Date")) {
                                toGetM = toObj.getClass().getMethod("set" + name, Date.class);
                            }

                            if (srcGetM != null && toGetM != null) {
                                Object value = srcGetM.invoke(srcObj);
                                toGetM.invoke(toObj, value);
                                System.out.println("attribute name:" + srcName + " -> " + value.toString());
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                            re = false;
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            re = false;
        }
        return re;
    }


    /**
     * 判断是否为邮箱
     *
     * @param email
     * @return
     */
    public static boolean isEmail(String email) {
        String str = "^([a-zA-Z0-9]*[-_]?[a-zA-Z0-9]+)*@([a-zA-Z0-9]*[-_]?[a-zA-Z0-9]+)+[\\.][A-Za-z]{2,3}([\\.][A-Za-z]{2})?$";
        Pattern p = Pattern.compile(str);
        Matcher m = p.matcher(email);
        //logger.info(m.matches()+"---");
        return m.matches();
    }

    /**
     * 判断是否为手机号
     *
     * @param mobiles
     * @return
     */
    public static boolean isMobileNO(String mobiles) {
        Pattern p = Pattern.compile("^((13[0-9])|(15[^4,\\D])|(18[0,5-9]))\\d{8}$");
        Matcher m = p.matcher(mobiles);
        // logger.info(m.matches()+"---");
        return m.matches();
    }

    /**
     * 根据前缀生成相应的key
     * head+日期+时间+随机数
     *
     * @param head
     * @param tail
     * @return
     */
    @SuppressWarnings("deprecation")
    public static String getKey(String head, String tail) {
        String tmpS = head.substring(0, 1);
        tmpS = tmpS + (new SimpleDateFormat("yyMMddHHmmSSS")).format(new Date());

        return tmpS + tail.substring(0, 1) + String.format("%04d", (int) (Math.random() * 10000));
    }

    public static String getKey(String head, String tail, int Seq) {
        String tmpS = head.substring(0, 1);
        tmpS = tmpS + (new SimpleDateFormat("yyMMddHHmmSSS")).format(new Date());

        return tmpS + tail.substring(0, 1) + String.format("%04d", Seq);
    }

    /**
     * 判断String在trim()后是否为空
     *
     * @param str
     * @return
     */
    public static boolean isEmpty(String str) {
        if (str == null || "null".equals(str) || str.length() < 1) return true;
        return StringUtils.isEmpty(StringUtils.trimToEmpty(str));
    }

    /**
     * 只取字母和数字
     *
     * @param oldstr
     * @return
     */
    public static String getASCNUM(String oldstr) {
        return oldstr.replaceAll("[^a-z^A-Z^0-9]", "");
    }

    public static String getASC(String oldstr) {
        return oldstr.replaceAll("[^a-z^A-Z]", "");
    }

    public static String getNUM(String oldstr) {
        if (oldstr != null)
            return oldstr.replaceAll("[^0-9]", "");
        else return "";
    }

    /**
     * 判断String在trim()后是否为空
     *
     * @param str
     * @return
     */
    public static boolean isNotEmpty(String str) {
        if (str == null) return false;
        return !StringUtils.isEmpty(StringUtils.trimToEmpty(str));
    }

    public static boolean isEmpty(Double str) {
        if (str == null) return true;
        return false;
    }

    public static boolean isNotEmpty(Double str) {
        if (str == null) return false;
        return true;
    }

    public static boolean isEmpty(Integer str) {
        if (str == null) return true;
        return false;
    }

    public static boolean isNotEmpty(Integer str) {
        if (str == null) return false;
        return true;
    }


    /**
     * list转数组
     *
     * @param list
     * @return
     */
    public static String[] listToStrArray(List list) {

        if (list == null || list.size() == 0)
            return null;

        Iterator iterator = list.iterator();
        String[] strArray = new String[list.size()];
        int i = 0;

        while (iterator.hasNext()) {
            strArray[i] = String.valueOf(iterator.next());
            i++;
        }
        return strArray;
    }

    /**
     * 验证[某字符串]是否存在于逗号分隔的字符串中
     *
     * @param str       【abc,123,www】
     * @param substr    【123】
     * @param sepatator 【,】
     * @return
     */
    public static boolean isExist(String str, String substr, String sepatator) {
        if (str == null || str.trim().equals(""))
            return false;
        if (substr == null || substr.trim().equals(""))
            return false;
        String[] strArr = str.split(sepatator);
        int size = strArr.length;
        for (int i = 0; i < size; i++) {
            if (strArr[i].equals(substr))
                return true;
        }
        return false;
    }

    public static String join(Object[] array, char separator) {
        if (array == null) {
            return null;
        }
        int arraySize = array.length;
        int bufSize = (arraySize == 0 ? 0 : ((array[0] == null ? 16 : array[0].toString().length()) + 1) * arraySize);
        StringBuffer buf = new StringBuffer(bufSize);

        for (int i = 0; i < arraySize; i++) {
            if (i > 0) {
                buf.append(separator);
            }
            if (array[i] != null) {
                buf.append(array[i]);
            }
        }
        return buf.toString();
    }


    public static void main(String[] args) {
        for (int i = 0; i < 150; i++) {
            System.out.println(getKey("Hdd", "Ddd"));
        }
    }

    /**
     * 1、如果用“.”作为分隔的话，必须是如下写法：String.split("\\."),这样才能正确的分隔开，不能用String.split(".");
     * 2、如果用“|”作为分隔的话，必须是如下写法：String.split("\\|"),这样才能正确的分隔开，不能用String.split("|");
     * “.”和“|”都是转义字符，必须得加"\";
     * 3、如果在一个字符串中有多个分隔符，可以用“|”作为连字符，比如：“acount=? and uu =? or n=?”,把三个都分隔出来，可以用String.split("and|or");
     *
     * @param originalFilename
     * @param sdiv
     * @return
     */
    public static String substringAfter(String originalFilename, String sdiv) {
        // TODO Auto-generated method stub

        String[] slist = originalFilename.split(sdiv);
        if (slist.length > 0)
            return slist[slist.length];

        return originalFilename;
    }


}
